package com.right.near.business.model.dto;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.right.near.common.utils.DateUtil;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * 用户信息
 *
 * @author: star
 * @date: 2022/7/18
 */
@Data
public class UserDetailDTO implements UserDetails {

    /**
     * ID
     */
    private String id;

    /**
     * 用户名称
     */
    private String userName;

    /**
     * 密码
     */
    private String password;

    /**
     * 角色
     */
    private List<String> roles;

    /**
     * 密码到期日
     */
    private Date expire;

    /**
     * 是否生效
     */
    private Boolean enabled;

    /**
     * 是否锁定
     */
    private Boolean locked;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isNotEmpty(this.roles)) {
            for (String role : this.roles) {
                List<GrantedAuthority> auths = new ArrayList<>();
                auths.add(new SimpleGrantedAuthority("ROLE_".concat(role)));
                return auths;
            }
        }
        return Collections.emptyList();
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    /**
     * 账户是否未过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return !Objects.nonNull(this.expire) || !DateUtil.getDateNow().after(this.expire);
    }

    /**
     * 账户是否未锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return this.locked;
    }

    /**
     * 密码是否未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return !Objects.nonNull(this.expire) || !DateUtil.getDateNow().after(this.expire);
    }

    /**
     * 账户是否生效
     */
    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
